#!/bin/bash
###
 # @Author: Lai Jun
 # @E-mail: laijun@nudt.edu.cn
 # @LastEditors: Lai Jun
 # @LastEditTime: 2021-12-07 09:26:36
### 
#  see https://gist.github.com/nathzi1505/858a140b4ab621209b0e71c8a55df221
# make sure you have cuda development env (plus cudnn) and build essentials
#  tested env: 
#  cuda toolkit 11.1
#  ubuntu 20.04 and opencv 4.2.0

OPENCV_VERSION=4.2.0
OPENCV_INSTALL_DIR=~/opencv_build/

sudo apt install build-essential cmake git pkg-config libgtk-3-dev \
    libavcodec-dev libavformat-dev libswscale-dev libv4l-dev \
    libxvidcore-dev libx264-dev libjpeg-dev libpng-dev libtiff-dev \
    gfortran openexr libatlas-base-dev python3-dev python3-numpy \
    libtbb2 libtbb-dev libdc1394-22-dev libopenexr-dev \
    libgstreamer-plugins-base1.0-dev libgstreamer1.0-dev

mkdir opencv-$OPENCV_VERSION
cd opencv-$OPENCV_VERSION
wget https://github.com/opencv/opencv/archive/refs/tags/$OPENCV_VERSION.tar.gz -O opencv-$OPENCV_VERSION.tar.gz 
tar axf opencv-$OPENCV_VERSION.tar.gz 

wget https://github.com/opencv/opencv_contrib/archive/refs/tags/$OPENCV_VERSION.tar.gz -O opencv_contrib_$OPENCV_VERSION.tar.gz
tar axf opencv_contrib-$OPENCV_VERSION.tar.gz

cd opencv-$OPENCV_VERSION && mkdir -p build && cd build

cmake -D CMAKE_BUILD_TYPE=RELEASE \
    -D CMAKE_INSTALL_PREFIX=$OPENCV_INSTALL_DIR \
    -D INSTALL_PYTHON_EXAMPLES=ON \
    -D INSTALL_C_EXAMPLES=OFF \
    -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib-$OPENCV_VERSION/modules \
    -D BUILD_opencv_python2=OFF \
    -D PYTHON_EXCUTABLE=/usr/bin/python3 \
    -D WITH_CUDA=ON \
    -D WITH_CUBLAS=ON \
    -D DCUDA_NVCC_FLAGS="-D_FORCE_INLINES" \
    -D CUDA_ARCH_BIN="7.5" \
    -D CUDA_ARCH_PTX="" \
    -D CUDA_FAST_MATH=ON \
    -D WITH_TBB=ON \
    -D WITH_V4L=ON \
    -D WITH_QT=ON \
    -D WITH_GTK=ON \
    -D WITH_OPENGL=ON \
    -D BUILD_EXAMPLES=ON ..

make -j8
